<template>
	<div class="login_background">
		<div class="login_background_front"></div>
		<div class="login_main">
			<div class="login-form enter-x">
				<a-card>
					<div class="login-header">
						<div class="logo">
							<img src="@/assets/img/logo.png" />
							<label>{{ systemDesc }}</label>
						</div>
					</div>
          <a-form ref="loginForm" :form="form" @submit="onSubmit">
            <a-alert type="error" :closable="true" v-show="error" :message="error" showIcon style="margin-bottom: 24px;" />
            <a-form-item>
              <a-input
                size="large"
                v-decorator="['username', {rules: [{ required: true, message: '请输入用户账号', whitespace: true}]}]"
                placeholder="用户账号"
              >
                <a-icon slot="prefix" type="user" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-input-password
                size="large"
                autocomplete="autocomplete"
                type="password"
                placeholder="密码"
                v-decorator="['password', {rules: [{ required: true, message: '请输入密码', whitespace: true}]}]"
              >
                <a-icon slot="prefix" type="lock" />
              </a-input-password>
            </a-form-item>
            <a-form-item v-if="systemConfig.captchaOpenFlag">
              <a-row :gutter="8">
                <a-col :span="17">
                  <a-input
                    v-decorator="['captcha',{rules: [{ required: true, message: '请输入验证码', whitespace: true}]}]"
                    placeholder="验证码"
                    size="large"
                  >
                    <a-icon slot="prefix" type="smile"/>
                  </a-input>
                </a-col>
                <a-col :span="7">
                  <img v-if="requestCodeSuccess" style="width:105px;height:35px;margin-top: 2px;" :src="randCodeImage" @click="handleChangeCheckCode"/>
                  <img v-else style="margin-top: 2px;" src="@/assets/img/checkcode.png" @click="handleChangeCheckCode"/>
                </a-col>
              </a-row>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" class="w-full" :loading="logging" round size="large" htmlType="submit">
                登录
              </a-button>
            </a-form-item>
          </a-form>
				</a-card>
			</div>
		</div>
    <UpdatePassword ref="updatePassword" :user="formData" :pwdExpiredFlag="pwdExpiredFlag" @ok="loginSuccess" />
	</div>
</template>

<script>
import { CAPTCHA } from '@/services/api'
import { mapActions, mapState, mapMutations } from 'vuex'
import { timeFix } from '@/utils/util'
import { getAction } from '@/services/manage'
import { Alert as AAlert } from 'ant-design-vue'
import UpdatePassword from './UpdatePassword'
export default {
  name: 'Login',
  components: { UpdatePassword, AAlert },
  data() {
    return {
      logging: false,
      error: '',
      form: this.$form.createForm(this),
      randCodeImage: '',
      requestCodeSuccess: false,
      currdatetime: '',
      pwdExpiredFlag: false,
      formData: {}
    }
  },
  computed: {
    systemAbbr() {
      return this.$store.state.setting.systemAbbr
    },
    systemDesc() {
      return this.$store.state.setting.systemDesc
    },
    ...mapState('setting', ['theme', 'systemConfig'])
  },
  methods: {
    ...mapActions('account', ['Login']),
    ...mapActions('setting', ['GetSystemConfig']),
    ...mapMutations('account', ['clearStorage']),
    onSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err) => {
        if (!err) {
          this.logging = true
          const data = this.form.getFieldsValue()
          if (this.systemConfig.captchaOpenFlag) {
            data.uuid = this.randCode
          }
          this.formData = data
          this.Login(data).then(this.afterLogin).catch(error => {
            this.requestFailed(error)
          }).finally(() => {
            this.logging = false
          })
        }
      })
    },
    afterLogin(res) {
      this.logging = false
      if (res.code === 200) {
        if (res.result?.user?.pwdExpiredFlag) {
          this.pwdExpiredFlag = true
          this.$refs.updatePassword.show(this.formData)
        } else {
          this.loginSuccess()
        }
      } else {
        this.error = res.message
      }
    },
    loginSuccess() {
      this.$router.push({ path: '/dashboard/analysis' }, () => {})
      this.$notification.success({
        message: '欢迎',
        description: `${timeFix()}，欢迎回来`
      })
    },
    handleChangeCheckCode() {
      this.currdatetime = new Date().getTime()
      getAction(CAPTCHA).then(res => {
        if (res.success) {
          this.randCodeImage = 'data:image/jpg;base64,' + res.result.image
          this.randCode = res.result.code
          this.requestCodeSuccess = true
        } else {
          this.$message.error(res.message)
          this.requestCodeSuccess = false
        }
      }).catch(() => {
        this.requestCodeSuccess = false
      })
    },
    requestFailed(err) {
      this.$notification[ 'error' ]({
        message: '登录失败',
        description: (err.data || {}).message || err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  },
  created() {
    this.GetSystemConfig().then(res => {
      if (res.success && res.result.captchaOpenFlag) {
        this.handleChangeCheckCode()
      }
    }).catch(err => {
      console.error(err)
    })
  }
}
</script>

<style lang="less" scoped>
  .common-layout{
    .top_ {
      text-align: center;
      .header_ {
        height: 44px;
        line-height: 44px;
        a {
          text-decoration: none;
        }
        .logo {
          height: 44px;
          vertical-align: top;
          margin-right: 16px;
          display: inline-block;
        }
        .title_ {
          font-size: 33px;
          color: @title-color;
          font-family: 'Myriad Pro', 'Helvetica Neue', Arial, Helvetica, sans-serif;
          font-weight: 600;
          position: relative;
          top: 2px;
        }
      }
      .desc {
        font-size: 14px;
        color: @text-color-second;
        margin-top: 12px;
        margin-bottom: 40px;
      }
    }
    .login{
      width: 368px;
      margin: 0 auto;
      @media screen and (max-width: 576px) {
        width: 95%;
      }
      @media screen and (max-width: 320px) {
        .captcha-button{
          font-size: 14px;
        }
      }
      .icon {
        font-size: 24px;
        color: @text-color-second;
        margin-left: 16px;
        vertical-align: middle;
        cursor: pointer;
        transition: color 0.3s;

        &:hover {
          color: @primary-color;
        }
      }
    }
  }
</style>

<style lang="less">
	@import 'login2';
</style>
